//
//  ThumpViewController.m
//  yigou
//
//  Created by 秦乾龙 on 17/1/17.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "ThumpViewController.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "Comment.h"
#import "Article.h"

@interface ThumpViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableArray *commentArr;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;
@end

@implementation ThumpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.limit = 5;
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"点赞"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    _commentArr = [NSMutableArray array];
    [self setUI];
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self request];
}
- (void) setUI
{
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,ScreenW , ScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    [self addRefreshHeader:_mainTableView];
    [self addLoadMoreFooter:_mainTableView];
}
//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}
//上拉加载
- (void)loadMore {
    if (self.pageToEnd) {
        [ViewFactory showInfoMsg:@"没有下一页了！"];
        [_mainTableView.footer endRefreshing];
        return;
    }
    
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/userCenter/getContentByUserToLike?page=%ld&limit=%ld", APIYIGOU, self.page,self.limit];
    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ViewFactory showLoading];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSArray *array = [[allDic objectForKey:@"data"] objectForKey:@"list"];
        if (array.count == 0) {
            [ViewFactory showInfoMsg:@"没有下一页了！"];
            
        }
        else if (array.count<_limit)
        {
            self.pageToEnd = YES;
        }
        self.page += 1;
        [_commentArr addObjectsFromArray: array];
        [ViewFactory dismissLoading];
        [_mainTableView reloadData];
        [_mainTableView.footer endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.footer endRefreshing];
        [ViewFactory dismissLoading];
        [ViewFactory showInfoMsg:@"加载失败"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
        [_mainTableView.footer endRefreshing];
    }];
}

- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/getContentByUserToLike?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit]
    ;
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"allDic ====%@",allDic);
        [_commentArr removeAllObjects];
        [_commentArr addObjectsFromArray:allDic[@"data"][@"list"]];
        [_mainTableView reloadData];
        self.page += 1;
        if (_commentArr.count == 0) {
            [self showNoData];
        } else {
            [self hideNoData];
        }
        [_mainTableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _commentArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    CGFloat spaceToTop = 30*kScale;
    CGFloat spaceToLeft = 30*kScale;
    CGFloat lableH = 42*kScale;
   // Comment *comment = [Comment mj_objectWithKeyValues:_commentArr[indexPath.section]];
    Article *article =[Article  mj_objectWithKeyValues:_commentArr[indexPath.section][@"content"]];
    UILabel *nameLable = [[UILabel alloc]init];
    
    nameLable.text =[NSString stringWithFormat:@"“%@”",_commentArr[indexPath.section][@"nick_name"]];
    nameLable.font = [UIFont systemFontOfSize:17];
    
    CGSize nameLableSize = [nameLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    nameLable.textColor = QINGColor;
    nameLable.frame = CGRectMake(spaceToLeft, spaceToTop - 2, nameLableSize.width, nameLableSize.height);
    [cell addSubview:nameLable];
    
    UILabel *defultLable = [[UILabel alloc]init];
    if ([article.content_type isEqualToString:@"00"])
    {
        defultLable.text = @"点赞了您的帖子";
    }
    else if ([article.content_type isEqualToString:@"01"])
    {
        defultLable.text = @"点赞了您的文章";
    }
    
    defultLable.font = [UIFont systemFontOfSize:15];
    CGSize deafultSize = [defultLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    defultLable.frame = CGRectMake(spaceToLeft+nameLableSize.width+10*kScale, spaceToTop, ScreenW, deafultSize.height);
    defultLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:defultLable];
    
    //时间
    UILabel *timeLable = [[UILabel alloc]init];
    NSDateFormatter  *dateFormatter = [[NSDateFormatter alloc]init];
    //        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dateFormatter dateFromString:_commentArr[indexPath.section][@"like_tm"]];
    //            NSString *createDateStr = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    NSDate *nowDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
    
    NSTimeInterval timeWrong = [zone secondsFromGMTForDate:nowDate];// 以秒为单位返回当前时间与系统格林尼治时间的差
    
    NSDate *dateNow = [nowDate dateByAddingTimeInterval:timeWrong];
    //            NSString *nowDateStr = [NSString stringWithFormat:@"%ld",(long)[nowDate timeIntervalSince1970]];
    NSTimeInterval time = [dateNow timeIntervalSinceDate:date];
    NSInteger time2 = time;
    
    if (time2/60/60/24>=1)
    {
        timeLable.text = [NSString stringWithFormat:@"%ld天之前",time2/60/60/24];
    }
    else if(time2/60/60>=1)
    {
        timeLable.text = [NSString stringWithFormat:@"%ld小时之前",time2/60/60];
    }
    else
    {
        timeLable.text = @"刚刚";
    }
    
    
    timeLable.font = [UIFont systemFontOfSize:12];
    CGSize timeLableSize = [timeLable sizeThatFits:CGSizeMake(MAXFLOAT, lableH)];
    timeLable.frame = CGRectMake(ScreenW-spaceToLeft-timeLableSize.width, spaceToTop, ScreenW, timeLableSize.height);
    timeLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:timeLable];
    
    CGFloat headerImageH = 164*kScale;
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 15*kScale+nameLable.frame.origin.y+nameLableSize.height, headerImageH, headerImageH);
    [headerImage sd_setImageWithURL:[NSURL URLWithString:article.cover_img] width:140 height:140];
    
    headerImage.layer.masksToBounds  = YES;
    [cell addSubview:headerImage];
    CGFloat typeLableH = 41*kScale;
    UILabel *typeLable = [[UILabel alloc]initWithFrame:CGRectMake(0 , 0, typeLableH, typeLableH)];
    typeLable.textColor = [UIColor whiteColor];
    typeLable.backgroundColor = ZallColorFromRGB(0x000000);
    if ([article.content_type isEqualToString:@"00"])
    {
        typeLable.text = @"话";
    }
    else if ([article.content_type isEqualToString:@"01"])
    {
        typeLable.text = @"文";
    }
    
    
    
    typeLable.textAlignment = NSTextAlignmentCenter;
    [headerImage addSubview:typeLable];
    UILabel *introdocLable = [[UILabel alloc]init];
    introdocLable.font = [UIFont systemFontOfSize:13];
    introdocLable.numberOfLines = 0;
    //        introdocLable.lineBreakMode =  NSLineBreakByTruncatingTail;
    introdocLable.textColor = [UIColor colorWithRed:34/255.0 green:34/255.0 blue:34/255.0 alpha:1.0];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 5;
    introdocLable.text = article.content_desc;
    introdocLable.textColor = ZallColorFromRGB(0x9e9e9e);
    CGSize introSize = [introdocLable sizeThatFits:CGSizeMake(ScreenW-(headerImageH+3*30*kScale), MAXFLOAT)];
    
    //        NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:style};
    //        introdocLable.attributedText = [[NSAttributedString alloc]initWithString:introdocLable.text attributes:attributes];
    
    if (introSize.height<headerImageH)
    {
        introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), introSize.height);
    }
    else
    {
        introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), headerImageH);
    }
    //            introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, kScreenW-(headerImageH+3*30*kScale), introSize.height);
    
    [cell addSubview:introdocLable];
    cell.frame = CGRectMake(0, 0, ScreenW, nameLable.frame.origin.y+nameLableSize.height+spaceToTop+15*kScale+headerImageH);
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSelector:@selector(cancleSelect) withObject:nil afterDelay:0.1f];
    
    
}
- (void)cancleSelect
{
    [_mainTableView deselectRowAtIndexPath:[_mainTableView indexPathForSelectedRow] animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //提前获取cell
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    //cell里面已经设置好了frame，这里就要返回cell的frame就可以了。
    return cell.frame.size.height;
}
//设置区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0.001;
    }
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
//修改状态栏字体
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
//返回
- (void)goPop
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
